import Tooltip from '@/components/tooltip'
import styles from './index.module.less'
import cm from 'classnames'
import { useEffect, useState, useMemo } from 'react'
import QuestionSvg from '@/svg/question'
import ScrollHorizonMenu from '@/components/scroll-horizon-menu'
import DateRanger from '@/components/dateranger'
import Pagination from '@/components/pagination'
import Table from '@/components/table'
import columns from './column'
import { getOrderView, getOrderList } from '@/api'
import { useSetState } from 'ahooks'
import AdminAuthority from '@/components/admin-authority'
import UserSelect from '@/components/user-select'
import { currUserRoles,userinfo } from '@/store'
import { useRecoilValue } from 'recoil'
import { ADMIN_ID } from '@/constant'
import { formatNumber } from '@/utils/utils'
import { useCacheSessionData } from '@/utils/hooks'

const statisticArr = [
  {
    id: 1,
    icon: '/images/s3.webp',
    label: '总订单数',
    tooltip: '当前选择时段你带来的订单总数',
    key: 'totalOrderCount',
  },
  {
    id: 2,
    icon: '/images/o2.webp',
    label: '有效订单数',
    tooltip: '当前选择时段已完成审核的订单数，这些订单的分成金额可参与提现',
    key: 'effectiveOrderCount',
  },
  {
    id: 3,
    icon: '/images/o3.webp',
    label: '审核中订单数',
    tooltip: '订单从生成起进入30天的审核期，以避免用户退款或异常订单等情况',
    key: 'auditOrderCount',
  },
  {
    id: 4,
    icon: '/images/o4.webp',
    label: '无效订单数',
    tooltip: '指因用户退款或异常订单等情况而导致的无效订单，这部分订单无法参与分成',
    key: 'invalidOrderCount',
  },
]

const Index = () => {
  const user = useRecoilValue(userinfo)
  const [cacheDate, updateCacheDate, clearDate] = useCacheSessionData('order_detail')
  const currentRole = useRecoilValue(currUserRoles)
  const [selectedDate, setSelectedDate] = useState(
    cacheDate ? { startDate: cacheDate.startDate, endDate: cacheDate.endDate } : DateRanger.LAST7DAYS
  )
  const [userIds, setUserIds] = useState(
    currentRole.current.actorType === ADMIN_ID ? undefined : [user.id]
  )
  const [staticData, setStaticData] = useSetState({
    total: {},
    list: null,
    page: 1,
    pageSize: 30,
    totalSize: 0,
  })

  const statisticParams = useMemo(() => {
    return { startTime: selectedDate.startDate, endTime: selectedDate.endDate, userIds }
  }, [selectedDate, userIds])

  const listParams = useMemo(() => {
    return {
      startTime: selectedDate.startDate,
      endTime: selectedDate.endDate,
      page: staticData.page,
      pageSize: staticData.pageSize,
      userIds,
    }
  }, [selectedDate, staticData.page, userIds])

  const updateIds = (data) => {
    setUserIds([...new Set(data)])
  }

  // 获取营销数据总览
  const getDataStatistic = async (data) => {
    const res = await getOrderView(data)
    if (!res.code) {
      setStaticData({ total: res.data || {} })
    }
  }
  //获取营销数据列表
  const getList = async (data) => {
    const res = await getOrderList(data)
    if (!res.code) {
      const data = res.data?.list || []
      setStaticData({ list: data, totalSize: res.data?.total || 0 })
    }
  }

  // 时间段修改
  const updateDate = (date) => {
    updateCacheDate(date)
    setSelectedDate(date)
  }

  useEffect(() => {
    getDataStatistic(statisticParams)
  }, [selectedDate, userIds])
  useEffect(() => {
    getList(listParams)
  }, [selectedDate, staticData.page, userIds])
  useEffect(() => {
    return () => {
      clearDate()
    }
  }, [])
  return (
    <div className={styles.home}>
      <div className="flex justify-between mb-10 pr-10">
        <DateRanger direction="left" onChange={updateDate} initDate={cacheDate ? cacheDate.dateObj : ''} />
        <AdminAuthority>
          <UserSelect onSubmit={(ids) => updateIds(ids)} />
        </AdminAuthority>
      </div>
      <ScrollHorizonMenu>
        {statisticArr.map((item, index) => {
          const TipDom = (
            <div className="tooltips">
              <QuestionSvg className="w-4 h-4 mr-1 shrink-0" fill="var(--theme-color)" />
              <span>{item.tooltip}</span>
            </div>
          )
          let count = 0
          try {
            count = staticData.total[item.key] || 0
          } catch (error) {}
          return (
            <div className={styles.statisticItem} key={index}>
              <div className={styles.itemInfo}>
                <div className={styles.infoTop}>
                  <span>{item.label}</span>
                  <Tooltip text={TipDom} />
                </div>
                <div className={cm(styles.infoBottom, !item.tip ? styles.notip : '')}>
                  <span className={styles.amount}>
                    {formatNumber(count, item.isMoney)}
                    {count >= 10000 && <span style={{ fontSize: 12, transform: 'scale(0.5)' }}>w</span>}
                  </span>
                </div>
              </div>
              <img src={item.icon} className={styles.itemImg} />
            </div>
          )
        })}
      </ScrollHorizonMenu>
      <p className={styles.dataDetail}>数据明细</p>
      <Table
        nullText="所选时段暂无数据～请重新选择"
        className={styles.tableMainContent}
        columns={columns()}
        dataSource={staticData.list}
        height={100}
        onChange={(e) => console.log('改变了', e)}
      />
      {staticData.totalSize > 30 && <Pagination total={staticData.totalSize || 0} className="mt-7" />}
    </div>
  )
}

export default Index
